import Toast from 'tdesign-miniprogram/toast/index';
import {
  baseURL
} from '../../../services/request';
import {
  getMenberDetail,
  addMenberData,
  editMenber,
  getRoleCode
} from '../../../services/api/menber';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    hideButton: false,
    cityValue: [],
    index: -1,
    //   areaLeader  saler
    roleCodeList: [],
    sexValue: ['未知', '男', '女'],
    editSelf: false,
    isEdit: false,
    showSaveBtn: false,
    popvisible: false,
    nickName: '',
    sex: '',
    parentRoleCode: '',
    nameValue: '',

    personInfo: {
      avatar: '',
      nickName: '',
      gender: '',
      userPhone: '',
      roleCode: '',
      pid: '',
      priceLevel: 0,
    },
    typeVisible: false,
    agentLevel: {
      value: '',
      name: '',
    },
    agentLevelValue: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var pages = getCurrentPages(); //获取加载的页面
    var currentPage = pages[pages.length - 1]; //获取当前页面的对象
    var {
      options
    } = currentPage; //如果要获取url中所带的参数可以查看options
    //  财务 hideButton  true  其他 false
    if (options.hideButton) {
      this.setData({
        hideButton: options.hideButton,
      });
    }

    //  判断当前页面是修改个人中心的资料页面 还是查看下级员工的详情页面
    if (options.editSelf) {
      wx.setNavigationBarTitle({
        title: '个人中心',
      });
      this.setData({
        editSelf: true,
        showSaveBtn: true,
      });
      this.getDetailData(options.kid);
      return;
    }
    this.getRoleData();
    if (options.isEdit) {
      this.setData({
        isEdit: options.isEdit,
        ['personInfo.pid']: options.pid,
        parentRoleCode: options.pRoleCode,
      });
      this.getDetailData(options.kid);
    } else {
      this.setData({
        showSaveBtn: true,
        ['personInfo.pid']: options.pid,
        parentRoleCode: options.pRoleCode,
      });
      wx.setNavigationBarTitle({
        title: '添加员工账号',
      });
    }
  },
  async getRoleData() {
    const {
      data,
      code
    } = await getRoleCode();
    this.setData({
      roleCodeList: data,
    });
  },
  editStatus() {
    this.setData({
      isEdit: false,
      showSaveBtn: true,
    });
  },
  onClickCellTerminal(e) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    wx.navigateTo({
      url: `/subpages/pages/allTerminal/allTerminal?agentUserId=${userId}`,
    });
  },
  onClickCellContact(e) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    wx.navigateTo({
      url: `/subpages/pages/contactor/contactor?agentUserId=${userId}`,
    })
  },

  onClickCellsaleTicket(e) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    wx.navigateTo({
      url: `/subpages/pages/saleOrder/saleOrder?orderId=${userId}`,
    })
  },
  onClickCellDistrict(e) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    wx.navigateTo({
      url: `/subpages/pages/terminalCount/visitorRecord?kid=${userId}`,
    })
  },

  async getDetailData(kid) {
    const res = await getMenberDetail({
      kid,
    });
    if (res.code == '200') {
      const result = res.data;
      this.setData({
        personInfo: {
          ...result,
        },
        sex: this.data.sexValue[res.data.gender],
        index: this.data.roleCodeList.findIndex((el) => el.key == result.roleCode),
      });
    }
  },
  //  编辑和保存
  save() {
    const roleIndex = this.data.roleCodeList.findIndex((el) => el.key == this.data.parentRoleCode);
    if (!this.data.editSelf) {
      // 角色配置不允许配置比父级账号更高的角色
      if (this.data.index <= roleIndex) {
        Toast({
          selector: '#t-toast',
          message: '角色配置不正确',
          icon: 'fail',
          duration: 1000,
        });
        return;
      }
    }

    const patten = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!patten.test(this.data.personInfo.userPhone)) {
      Toast({
        selector: '#t-toast',
        message: '请填写正确的手机号码',
        icon: '',
        duration: 1000,
      });
      return;
    }
    var pages = getCurrentPages(); //获取加载的页面
    var currentPage = pages[pages.length - 1]; //获取当前页面的对象
    var {
      options
    } = currentPage; //如果要获取url中所带的参数可以查看options

    if (options.isEdit || options.editSelf) {
      this.editData();
    } else {
      this.saveData();
    }
  },
  async editData() {
    var patrn = /^(\w){6,20}$/;
    console.log(this.data.personInfo.userPwd);
    if (this.data.personInfo.userPwd) {
      if (!patrn.test(this.data.personInfo.userPwd)) {
        Toast({
          selector: '#t-toast',
          message: '新密码6-20个字母、数字、下划线',
          icon: '',
          duration: 1000,
        });
        return;
      }
    }
    const {
      code,
      data
    } = await editMenber({
      ...this.data.personInfo,
      roleCode: this.data.personInfo.roleCode,
      pid: this.data.editSelf ? '' : this.data.personInfo.pid,
    });
    if (code == '200') {
      wx.navigateBack({
        delta: 0,
      });
    }
  },
  onPhoneInput(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;
    this.setData({
      [key]: value,
    });
  },
  async saveData() {
    const {
      code,
      data
    } = await addMenberData({
      ...this.data.personInfo,
      roleCode: this.data.personInfo.roleCode,
    });
    if (code == '200') {
      wx.navigateBack({
        delta: 0,
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  onConfirm(e) {
    const {
      value
    } = e.detail;
    console.log(e.detail);
    this.setData({
        typeVisible: false,
        'agentLevel.value': value,
        'agentLevel.name': e.detail.target.name,
      },
      // () => {
      //   Toast({
      //     context: this,
      //     selector: '#t-toast',
      //     message: '设置成功',
      //     theme: 'success',
      //   });
      // },
    );
  },
  onWithoutTitlePicker() {
    this.setData({
      typeVisible: true,
    });
  },
  sexChoise() {},
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;
    const {
      nickName
    } = this.data.personInfo;

    switch (dataset.type) {
      case 'gender':
        this.setData({
          typeVisible: true,
        });
        break;
      case 'name':
        wx.navigateTo({
          url: `../name-edit/index?name=${nickName}`,
        });
        break;
      case 'avatarUrl':
        this.toModifyAvatar();
        break;
      default: {
        break;
      }
    }
  },

  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    const roleIndex = this.data.roleCodeList.findIndex((el) => el.key == this.data.parentRoleCode);
    if (e.detail.value <= roleIndex) {
      Toast({
        selector: '#t-toast',
        message: '角色配置不正确',
        icon: 'fail',
        duration: 1000,
      });
      return;
    }
    this.setData({
      index: e.detail.value,
      ['personInfo.roleCode']: this.data.roleCodeList[e.detail.value].key,
    });
  },
  bindSexChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    this.setData({
      ['personInfo.gender']: e.detail.value,
      sex: this.data.sexValue[e.detail.value],
    });
  },

  async toModifyAvatar() {
    const self = this;
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              path,
              size
            } = res.tempFiles[0];
            if (size <= 10485760) {
              const role = wx.getStorageSync('role');
              wx.uploadFile({
                url: `${baseURL}fileserver/pt/fileserver/action/upload`,
                filePath: path,
                name: 'file',
                header: {
                  devType: 4,
                  userId: role.userId,
                  token: role.tokenId,
                  appId: 'crm_agent',
                  authType: 'agent',
                },
                success: function (result) {
                  if (JSON.parse(result.data).code == 200) {
                    const resourceUrl = JSON.parse(result.data).data.urlPath;
                    console.log(resourceUrl);
                    self.setData({
                      'personInfo.avatar': resourceUrl,
                    });
                  }
                },
              });
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传',
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      const tempUrlArr = tempFilePath.split('/');
      const tempFileName = tempUrlArr[tempUrlArr.length - 1];
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
    }
  },
  onClickCellpassword() {
    wx.navigateTo({
      url: '/pages/usercenter/name-edit/index',
    });
  },
});